import { Form } from '@ant-design/compatible';
import AuthComponent from '@/components/Authorized/AuthComponent';
import '@ant-design/compatible/assets/index.css';
import { DatePicker, message, Input, Select, Button, Modal } from 'antd';
import router from 'umi/router';
import React, { useState, useCallback, useRef, useEffect } from 'react';
import ProTable from '@ant-design/pro-table';
import { useRequest } from '@umijs/hooks';
import { connect } from 'dva';
import { vipPaxInfoPage, queryCityInfo, exportVipPaxInfo, getPaxType,getUserBindRoom } from './service';
import moment from 'moment';
import styles from './index.less';
import { useActivate } from 'react-activation';
import { formatFlightNo, controlTableHeight } from '@/utils/pagesGeneralMethods'; // 页面通用方法
import VipGreet from '../vipAccess/components/vipGreet'; //迎接

const { Option } = Select;

const VipAccess = props => { 
  const { data: paxTypeData } = useRequest(getPaxType,{loadingDelay: true}); //获取旅客类别
  const { data: selectData } = useRequest(queryCityInfo, { loadingDelay: true }); //获取出发和到达航站
  // 选中的贵宾室数据
  const [vipRoomObj, setVipRoomObj] = useState({});

  const { run: getUserBindRoomFun} = useRequest(getUserBindRoom, { 
    loadingDelay: true,
    onSuccess:(data)=>{
      // 获取登录用户绑定贵宾室信息
      if (data?.length > 0) {
        setVipRoomObj(data[0]);
      }else{
        setVipRoomObj({});
      }
    }
  }); //当前登录用户的绑厅信息
  // 页面缓存之后，再次打开更新贵宾厅数据
  useActivate(() => {
    getUserBindRoomFun();
})
  const [exportFlag, handleExportFlag] = useState(false); // 导出数据的标志
  const [searchParams, setSearchParams] = useState(null); //查询参数
  const [openType, setOpenType] = useState('click'); //区别点击还是扫描
  const [vipGreetVisible, setVipGreetVisible] = useState(false)// 迎接弹框

  const [isCollapse, controlC] = useState(true); //搜索面板是否折叠
  const [selectRow, setSelectRow] = useState([]); // 选中的项

  const actionRef = useRef();
  const ref = useRef();
  // 搜索前的回调
  const beforeSearchSubmit = useCallback(params => {
    params['lclDptDate'] = params.lclDptDate ? params.lclDptDate.format('YYYY-MM-DD') : '';
    params['orgCityAirp'] = params.orgCityAirp ? params.orgCityAirp : '';
    if (
      event.target.querySelector('span') &&
      event.target.querySelector('span').innerText === '重 置'
    ) {
      ref.current &&
        ref.current.setFieldsValue({
          lclDptDate: moment(),
          orgCityAirp: "CTU"
        });
    }
    setSearchParams(params);
    return params;
  }, []);

  // 刷新表格数据
  const reloadTable = useCallback(function () {
      actionRef?.current?.reload();
  }, []);

  // 选中项
  const changeRows = (selectedRowKeys, selectedRows) => {
    setSelectRow([...selectedRows]);
  };
  const showAuditModal = () => {
    if (Object.keys(vipRoomObj).length == 0) {
      return message.error('请先绑定贵宾室');
    }
    if (selectRow.length !== 1) {
      return message.error('请选择一位旅客进行迎接操作');
    }
    if (selectRow[0].memo) {
      Modal.info({
        title: `${selectRow[0].paxName} 旅客`,
        content: (
          <div>
            <p>旅客喜好：</p>
            <p>旅客备注：{selectRow[0].memo}</p>
          </div>
        ),
        onOk() {
          setOpenType('click');
          setVipGreetVisible(true);
        },
      });
    }else{
        setOpenType('click');
        setVipGreetVisible(true);
    }
    
  };

  //  贵宾旅客查询报表导出
  const handleExport = () => {
    if (!exportFlag) {
      message.error('表格数据为空');
      return false;
    }
    const hide = message.loading('正在导出');
    let res = exportVipPaxInfo(searchParams).then(res => {
        let blob = new Blob([res], {
          type: 'application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        });
        let elink = document.createElement('a');
        let time = moment(Date.now()).format('YYYY-MM-DD HH_ss_mm');
        elink.download = '贵宾旅客查询报表' + time + '.xls';
        elink.style.display = 'none';
        elink.href = URL.createObjectURL(blob);
        document.body.appendChild(elink);
        elink.click();
        document.body.removeChild(elink);
        hide();
        message.success('导出成功');
      })
      .catch(err => {});
  };

  // 列表项
  const columns = [
    {
      title: 'PNR',
      width: 120,
      dataIndex: 'pnrRef',
      hideInSearch: true,
    },
    {
      title: '航班状态',
      dataIndex: 'flightStatus',
      hideInSearch: true,
      width: 90,
      filters: false,
      valueEnum: {
          null: {
            text: '正常',
          },
          'D': {
            text: '延误',
          },
          'C': {
            text: '取消',
          },
          'N': {
            text: '正常',
          },
        },
    },
    {
      title: '航班日期',
      width: 90,
      dataIndex: 'lclDptDate',
      key: 'lclDptDate',
      order: 1,
      renderFormItem: (_, { ...rest }) => {
        const format = 'YYYY-MM-DD';
        return (
          <DatePicker style={{ width: '100%' }} format={format} allowClear={false} {...rest} />
        );
      },
    },
    {
      title: '航班号',
      width: 90,
      dataIndex: 'flightNo',
      order: 10,
      renderFormItem: (_, { defaultRender, ...rest }) => {
        return (
          <Input
            {...rest}
            onChange={e => {
              e.target.value = formatFlightNo(e.target.value);
              rest.onChange(e.target.value);
            }}
            allowClear
            maxLength={6}
            placeholder="3U"
          />
        );
      },
    },
    {
      title: '机号',
      hideInSearch: true,
      filters: false,
      dataIndex: 'planeCode',
      width: 120,
    },
    {
      title: '起飞时间',
      hideInSearch: true,
      filters: false,
      dataIndex: 'std',
      width: 180,
    },
    {
      title: '登机口',
      filters: false,
      order: 7,
      dataIndex: 'gate',
      width: 120,
      renderFormItem: (_, { defaultRender, ...rest }) => {
        return <Input
          {...rest}
          onChange={e => {
            e.target.value= e.target.value.replace(/[^0-9a-zA-Z]/g,'');
            rest.onChange(e.target.value)
          }}
          allowClear maxLength={8} placeholder="请输入" />;
      }
    },
    {
      title: (_, type) => (type === 'table' ? '始发地' : '起飞航站'),
      dataIndex: 'org',
      key: 'orgCityAirp',
      order: 6,
      width: 130,
      renderFormItem: (_, { ...rest }, form) => {
        return (
          <Select
            allowClear={true}
            showSearch
            placeholder="请选择"
            defaultActiveFirstOption={false}
            showArrow={false}
            filterOption={true}
            optionFilterProp="children"
            notFoundContent={null}
            {...rest}
          >
            {selectData &&
              selectData.map((v, i) => {
                return (
                  <Option key={v.CITY3CODE} value={v.CITY3CODE}>
                    {v.CITYNAME}-{v.CITY3CODE}
                  </Option>
                );
              })}
          </Select>
        );
      },
    },
    // 到达
    {
      title: (_, type) => (type === 'table' ? '目的地' : '到达航站'),
      dataIndex: 'dst',
      key: 'dstCityAirp',
      order: 5,
      width: 100,
      renderFormItem: (_, { ...rest }, form) => {
        return (
          <Select
            allowClear={true}
            showSearch
            placeholder="请选择"
            defaultActiveFirstOption={false}
            showArrow={false}
            filterOption={true}
            optionFilterProp="children"
            notFoundContent={null}
            {...rest}
          >
            {selectData &&
              selectData.map((v, i) => {
                return (
                  <Option key={v.CITY3CODE} value={v.CITY3CODE}>
                    {v.CITYNAME}-{v.CITY3CODE}
                  </Option>
                );
              })}
          </Select>
        );
      },
    },
    
    {
      title: '航线',
      hideInSearch: true,
      dataIndex: 'fltRoute',
      width: 130,
    },
    {
      title: '旅客姓名',
      dataIndex: 'paxName',
      order: 9,
      width: 130,
    },
    {
      title: '随行人数',
      hideInSearch: true,
      dataIndex: 'alongs',
      width: 130,
    },
    {
      title: '联系方式',
      ellipsis: true,
      hideInSearch: true,
      dataIndex: 'phoneNo',
      width: 130,
      render:(_) => {
        return <div style={{height:"6px"}} >{_}</div>
      },
    },
    {
      title: '旅客类型',
      ellipsis: true,
      dataIndex: 'paxTypeDesc',
      key: 'paxTypeCode',
      order: 2,
      width: 180,
      render:(_) => {
        return <div style={{height:"6px"}} >{_}</div>
      },
      renderFormItem: (_, { ...rest }, form) => {
        return (
          <Select
            allowClear={false}
            showSearch
            placeholder="请选择旅客类型"
            defaultActiveFirstOption={false}
            showArrow={false}
            filterOption={true}
            optionFilterProp="children"
            notFoundContent={null}
            {...rest}
          >
            {
                paxTypeData && paxTypeData.map((v, i) => {
                    return (
                    <Option key={v.paxTypeCode} value={v.paxTypeCode}>{v.paxTypeName}</Option>
                    )
                })
            }
            <Option value="">全部</Option>
          </Select>
        );
      },
    },

    {
      title: '旅客状态',
      hideInSearch: true,
      dataIndex: 'paxStatus',
      width: 130, 
      valueEnum: {
        '': {
          text: '全部',
        },
        '1': {
          text: '已迎接',
        },
        '2': {
          text: '已送别',
        },
        '3': {
          text: '已拒绝',
        },
        // '4': {
        //   text: '未迎接',
        // },
      },
    },
    {
      title: '备注信息',
      ellipsis: true,
      hideInSearch: true,
      dataIndex: 'memo',
      width: 180,
      render:(_) => {
        return <div style={{height:"6px"}} >{_}</div>
      },
    },
    {
      title: '操作人员',
      hideInSearch: true,
      dataIndex: 'sysUser',
      width: 100,
    },
  ];
  return (
    <div id="parentBox">
      <ProTable
        options={{ density: false, fullScreen: true, reload:false, setting: true }}
        size="small"
        formRef={ref}
        scroll={{ x: 1000, y: controlTableHeight(isCollapse, 360, 470) }}
        className={styles.vipPaxQuery}
        headerTitle={
          <span style={{ paddingRight: 10, fontWeight: 'bold', color: '#000' }}>贵宾列表</span>
        }
        toolBarRender={() => [
          <AuthComponent authCode="vip.vipPaxQuery.download">
            <Button type="primary" onClick={showAuditModal}>
              迎接
            </Button>
          </AuthComponent>,
          <AuthComponent authCode="vip.vipPaxQuery.greet">
            <Button type="primary" onClick={handleExport}>
              报表
            </Button>
          </AuthComponent>,
        ]}
        search={{
          onCollapse: val => {
            controlC(val);
          },
          span: {
            //设置排列方式
            xs: 24,
            sm: 24,
            md: 8,
            lg: 8,
            xl: 8,
            xxl: 8,
          },
        }}
        actionRef={actionRef}
        formRef={ref}
        dateFormatter="YYYY-MM-DD"
        pagination={{
          showSizeChanger: true,
          showTotal: (total, range) => `${range[0]}-${range[1]} 共 ${total} 项`,
        }}
        rowKey="paxId"
        beforeSearchSubmit={beforeSearchSubmit}
        request={params => {
          if (!params['lclDptDate']) {
            params['lclDptDate'] = moment().format('YYYY-MM-DD');
            ref.current && ref.current.setFieldsValue({
              lclDptDate: moment(),
            });
          }
          if (!params['paxTypeCode']) {
            ref.current && ref.current.setFieldsValue({
              paxTypeCode: "",
            });
          }
          if (!('orgCityAirp' in params)) {
            params['orgCityAirp'] = "CTU"
            ref.current && ref.current.setFieldsValue({
              orgCityAirp: "CTU",
            });
          }
          setSearchParams(params);
          return vipPaxInfoPage({ ...params });
        }}
        postData={data => {
          handleExportFlag(data.length === 0 ? false : true);
          // console.log('data返回', data);
          return data;
        }}
        columns={columns}
        rowSelection={{ onChange: changeRows }}
        tableAlertRender={false} //选中提示
      />

      {/* 页面自定义组件 start*/}
      {/* 迎接 */}
      <VipGreet {...{ 
        vipGreetVisible, 
        setVipGreetVisible,
        // scanCode,
        openType,
        selectData,
        vipRoomObj,
        reloadTable,
        paxTypeData,
        selectRow
      }} />
      {/* 页面自定义组件 end*/}
    </div>
  );
};

export default Form.create()(VipAccess);
